﻿#--coding:utf-8--
from django.db import models
from django.contrib.auth import  models as auth_models
import datetime
import managers
import re
from django.template.defaultfilters import slugify

STATUS_CHOICES = (
    (0, 'Not set'),
    (1, 'Todo'),
    (2, 'Done')
    )
class Tag(models.Model):
    """
    A descriptive tag to be applied to a Snippet.

    """
    name = models.CharField(maxlength=50, unique=True)
    slug = models.SlugField(editable=False)

    class Meta:
        ordering = ('name',)

    objects = managers.TagsManager()
    
    class Admin:
        pass
    
    def slugify(self,value):
        "Converts to lowercase, removes non-alpha chars and converts spaces to hyphens"
        value = re.sub('[\s-]', '', value).strip().lower()
        return re.sub('[-\s]+', '-', value)
    
    def save(self):
        if not self.id:
            self.slug = self.slugify(self.name)
        super(Tag, self).save()

    def get_absolute_url(self):
        return "/tags/%s/" % self.slug

    def __str__(self):
        return self.name
    

    
class Tip(models.Model):
    title=models.CharField(maxlength=100,editable=False)
    content=models.TextField()
    pub_date=models.DateTimeField(auto_now=True)
    author=models.ForeignKey(auth_models.User)
    #alert or feed output time
    due_time=models.DateTimeField(auto_now_add=True)
    #dostatus 0 notset 1 -todo 2-done
    dostatus=models.IntegerField(default=0,choices=STATUS_CHOICES)
    tag_list = models.CharField(maxlength=250,
                                help_text="Separate tags with spaces. Maximum 250 characters.")
    tags = models.ManyToManyField(Tag, editable=False)

    def __str__(self):
        return self.title
    
    def get_absolute_url(self):
        return "/tip/%s/" % self.id

    objects = managers.TipsManager()
    
    class Admin:
         fields = (
                    ('tip detail', {'fields': ('content','author','tag_list')}),
                    ('date infomation', {'fields': ('pub_date','due_time')}),
                    ('status',{'fields':('dostatus',)})
                    )
         list_display = ('title', 'pub_date','tag_list')
         list_filter = ['pub_date']
         date_hierarchy = 'pub_date'

    def save(self):
        if not self.id:
            self.pub_date = datetime.datetime.now()
        self.tag_list = self.tag_list.lower() # Normalize to lower-case
        self.content=self.content.lstrip()
        lines=self.content.splitlines()
        if len(lines)>0:
            self.title=lines[0][:100]
        else:
            self.title='untitled'
        super(Tip, self).save()

        # Now that the Snippet is saved, deal with the tags.
        current_tags =list(self.tags.all()) # We only want to query this once.
        new_tag_list = self.tag_list.split(',')

        # First, clear out tags that aren't on the Snippet anymore.
        for tag in current_tags:
            if unicode(tag.name,'utf-8') not in new_tag_list:
                self.tags.remove(tag)

        # Then add any new tags.
        for tag_name in new_tag_list:
            if tag_name not in [unicode(tag.name,'utf-8') for tag in current_tags]:
                tag, created = Tag.objects.get_or_create(name=tag_name)
                self.tags.add(tag)
    
    